// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <sstream>

#include <nebula/compute/ordering.h>
#include <turbo/log/logging.h>

namespace nebula::compute {

    bool SortKey::equals(const SortKey &other) const {
        return target == other.target && order == other.order;
    }

    std::string SortKey::to_string() const {
        std::stringstream ss;
        ss << target.to_string() << ' ';
        switch (order) {
            case SortOrder::Ascending:
                ss << "ASC";
                break;
            case SortOrder::Descending:
                ss << "DESC";
                break;
        }
        return ss.str();
    }

    bool Ordering::is_suborder_of(const Ordering &other) const {
        if (sort_keys_.empty()) {
            // The implicit ordering is a subordering of nothing.  The unordered ordering
            // is a subordering of everything
            return !is_implicit_;
        }
        if (null_placement_ != other.null_placement_) {
            return false;
        }
        if (sort_keys_.size() > other.sort_keys_.size()) {
            return false;
        }
        for (std::size_t key_idx = 0; key_idx < sort_keys_.size(); key_idx++) {
            if (sort_keys_[key_idx] != other.sort_keys_[key_idx]) {
                return false;
            }
        }
        return true;
    }

    bool Ordering::equals(const Ordering &other) const {
        return null_placement_ == other.null_placement_ && sort_keys_ == other.sort_keys_;
    }

    std::string Ordering::to_string() const {
        std::stringstream ss;
        ss << "[";
        bool first = true;
        for (const auto &key: sort_keys_) {
            if (first) {
                first = false;
            } else {
                ss << ", ";
            }
            ss << key.to_string();
        }
        ss << "]";
        switch (null_placement_) {
            case NullPlacement::AtEnd:
                ss << " nulls last";
                break;
            case NullPlacement::AtStart:
                ss << " nulls first";
                break;
            default:
                unreachable("");
        }
        return ss.str();
    }

}  // namespace nebula::compute
